import { t } from 'i18next'
import React, { FC, useEffect, useRef, useState } from 'react'
import {
	IconActionMore,
	ItemActionWrap,
	OperateDropDownWrap,
	operateType,
	OperateIconComponent,
	DropDownComponent,
} from '../../../../../../components'
import { Trigger, TriggerInstance } from '@kedacom/react-next'
import { OrgModel } from '@/api/manager/organize/interface'
import { useAIStore } from '../../../../../ai/store'
import { useTimeout } from 'ahooks'
import { fetchPowerOnOne } from '@/api/manager/ai'
import { useMccStore } from '@/pages/manager/store'
import shallow from 'zustand/shallow'
import { Mt } from '@/api/manager/mt'
import { useParamsStore } from '../../../../store'

interface ItemActionProps {
	mcc: Mt
	status: OrgModel['status']
	propWidth: number
}

type operateAllType = operateType | 'offline'

interface IconOperate {
	icon: operateAllType[]
	dropDown: operateAllType[]
}

const useOperate = (mcc: Mt, isSuperMeeting: boolean, isKisDevice: boolean) => {
	const result = useParamsStore((state) => state.tableItemAction)
	if (!mcc.mtid && mcc.confLevel !== 2 /**下级离线(删除隐藏)*/) {
		return { icon: ['offline', 'mtInfo'], dropDown: [] } as IconOperate
	}
	if (isSuperMeeting) {
		if (mcc.status.isOnline) {
			return { icon: ['online', 'oftenMt', 'mtInfo', 'delete'], dropDown: [] } as IconOperate
		} else {
			return { icon: ['offline', 'oftenMt', 'mtInfo', 'delete'], dropDown: [] } as IconOperate
		}
	}
	//是否在线
	if (mcc.status.isOnline) {
		return result.mt
	} else {
		if (isKisDevice) {
			return { icon: ['offline', 'kis', 'mtInfo', 'delete'], dropDown: [] } as IconOperate
		} else {
			return { icon: ['offline', 'mtInfo', 'delete'], dropDown: [] } as IconOperate
		}
	}
}

export const ItemAction: FC<ItemActionProps> = ({ mcc, status, propWidth }) => {
	const { meetingMoid, isSuperMeeting, isCustomMix } = useMccStore(
		(state) => ({
			meetingMoid: state.mccInfo.meetingMoid,
			isSuperMeeting: state.mccInfo.superMtNum === 1,
			isCustomMix: state.mixMode === 2,
		}),
		shallow
	)
	const [kis, setKis] = useState({
		isKisDevice: false,
		operation: false,
		showCalling: false,
	})
	const [interval, setInterval] = useState<number | undefined>(undefined)
	useTimeout(() => {
		setKis({
			isKisDevice: true,
			operation: kis.operation,
			showCalling: false,
		})
		setInterval(undefined)
	}, interval)
	const kisOnclick = (mcc: Mt) => {
		setKis({
			isKisDevice: true,
			operation: kis.operation,
			showCalling: true,
		})
		fetchPowerOnOne(mcc, meetingMoid, isSuperMeeting).then((res) => {
			//此处存在闭包问题  showCalling不能取kis.showCalling  值为false时 组件删除  点击事件取缓存
			if (res) {
				setKis((v) => ({
					...v,
					isKisDevice: true,
					operation: res.operation === 1,
				}))
			}
		})
		setInterval(2000)
	}
	useEffect(
		() =>
			useAIStore.subscribe(
				(x) => x.kisList,
				(kisList) => {
					let kisItem = kisList.find((item) => item.mtKey === mcc.mtKey)
					if (kisItem) {
						setKis({
							isKisDevice: true,
							operation: kisItem.operation,
							showCalling: kisItem.showCalling.org,
						})
					} else {
						setKis({
							isKisDevice: false,
							operation: false,
							showCalling: false,
						})
					}
				}
			),
		[]
	)
	const { icon, dropDown } = useOperate(mcc, isSuperMeeting, kis.isKisDevice)
	const triggerRef = useRef<TriggerInstance>()
	return (
		<ItemActionWrap style={{ width: propWidth }}>
			{!status.isCalling ? (
				!kis.showCalling ? (
					<div className="action-icons">
						{icon.map((x) => OperateIconComponent[x](mcc, { isCustomMix, isSuperMeeting, kisOnclick }))}
						{dropDown.length > 0 && (
							<Trigger
								trigger={['click']}
								ref={triggerRef}
								popup={
									<OperateDropDownWrap
										className="operate-popup__i18n"
										onClick={() => {
											triggerRef.current?.close()
										}}
									>
										<ul>
											{dropDown.map((x) =>
												DropDownComponent[x](mcc, { isCustomMix, isSuperMeeting })
											)}
										</ul>
									</OperateDropDownWrap>
								}
								preventOverflow
								popupAlign={{
									points: ['bl', 'tl'],
									offset: [0, 3],
								}}
							>
								<IconActionMore />
							</Trigger>
						)}
					</div>
				) : kis.operation ? (
					<div className="isCalling">{t('已开机')}</div>
				) : (
					<div className="isCalling">{t('正在开机...')}</div>
				)
			) : (
				<div className="isCalling">{t('正在呼叫中...')}</div>
			)}
		</ItemActionWrap>
	)
}
